package ystp.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ystp.model.Ysuser;
import ystp.model.Ysxiangmu;
import ystp.service.YsuserService;
import ystp.service.YsxiangmuService;
import ystp.support.BooleanMessage;
import ystp.support.JsonResult;
import ystp.support.PageInfo;
import ystp.support.StringHandle;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("user")
public class YsuserController {
    @Resource
    YsuserService ddService;

    @Resource
    YsxiangmuService ddYsxiangmuService;

    public Logger log = LoggerFactory.getLogger(YsuserController.class);

    @RequestMapping("check_login")
    public JsonResult<?> checkLogin(@RequestParam("account") String ppAccount,
                                    @RequestParam("password") String ppPassword,
                                    @RequestParam("yzm") String ppYzm,
                                    HttpServletRequest request){
        try {
            ppAccount = ppAccount.trim();
            ppPassword = ppPassword.trim();
            ppYzm = ppYzm.trim();
            HttpSession session = request.getSession();
//            String mmYzm = session.getAttribute("checkcode").toString();

//            if(!ppYzm.equals(mmYzm)) {
//                return JsonResult.getErrorResult("登录失败！验证码不正确。");
//            }

            Ysuser mmYsuser = ddService.checkLogin(ppAccount, ppPassword);
            if(mmYsuser == null) {
                return JsonResult.getErrorResult("登录失败！用户名密码错误 或 账号无效。");
            }


            session.setAttribute("Id", mmYsuser.getUserid());
            session.setAttribute("TrueName", mmYsuser.getUsername());
            session.setAttribute("Type", mmYsuser.getUsertype());
            session.setMaxInactiveInterval(60*60*12);//过期时间12小时

            Ysxiangmu mmYltpXiangmu=ddYsxiangmuService.getIsactivedxiangmu();

            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("Type", mmYsuser.getUsertype());
            if(mmYltpXiangmu!=null){
                mmMap.put("XiangmuType", mmYltpXiangmu.getXiangmuleixing());
            }

            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("user/check_login:error",e);
            return JsonResult.getErrorResult("user/check_login:error " + e.getMessage());
        }
    }

    @RequestMapping("logout")
    public boolean loginout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("Id");
        session.removeAttribute("TrueName");
        session.removeAttribute("Type");
        return true;
    }

    @RequestMapping("find_one")
    public JsonResult<?> find_one(@RequestParam("userID") String ppUserId) {
        try {
            return JsonResult.getSuccessResult(ddService.findOne(ppUserId));

        }catch (Exception e) {
            e.printStackTrace();
            log.error("user/find_one:error",e);
            return JsonResult.getErrorResult("user/find_one:error " + e.getMessage());
        }
    }
    @RequestMapping("find_all")
    public JsonResult<?> find_all(@RequestParam("username") String ppuserName){
        try {
            return JsonResult.getSuccessResult(ddService.findAll(ppuserName));
        }catch (Exception e) {
            e.printStackTrace();
            log.error("user/find_all:error",e);
            return JsonResult.getErrorResult("user/find_all:error " + e.getMessage());
        }
    }



    @RequestMapping("findvaild")
    public JsonResult<?> findvaild(@RequestParam("username") String ppUsername,
                                   @RequestParam("pageindex") int ppPageIndex,
                                   @RequestParam("pagesize") int ppPageSize){
        try {
            if(!ppUsername.equals("")) {
                ppUsername = "%" + ppUsername + "%";
            }
            List<Map<String, Object>> mmList=ddService.findVaild(ppUsername,ppPageIndex,ppPageSize);
            Integer mmCount = ddService.getCountByisvalid(ppUsername);
            PageInfo mmPageInfo = new PageInfo(ppPageIndex, ppPageSize, mmCount);

            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("RenYuanList", mmList);
            mmMap.put("PageInfo", mmPageInfo);
            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("user/findvaild:error",e);
            return JsonResult.getErrorResult("user/findvaild:error " + e.getMessage());
        }
    }

    @RequestMapping("add")
    public JsonResult<?> add(@RequestParam("username") String ppusername,
                             @RequestParam("account") String ppaccount,
                             @RequestParam("password") String pppassword,
                             @RequestParam("buzhibie") String ppbuzhibie,
                             HttpServletRequest request) {

        try {

            String mmUserId= UUID.randomUUID().toString();

            Ysuser mmUser =new Ysuser();
            mmUser.setUserid(mmUserId);
            mmUser.setCreatetime(new Date());
            HttpSession session = request.getSession();
            mmUser.setCreateby(session.getAttribute("Id").toString());
            mmUser.setShifouxiugai("0");
            BooleanMessage mmBooleanMessage = checkInputData(mmUser,ppusername,ppaccount,pppassword,ppbuzhibie);

            if (!mmBooleanMessage.isOk()) {
                log.error("uesr/add:error",mmBooleanMessage.getMessage().toString());
                return JsonResult.getErrorResult(mmBooleanMessage.getMessage().toString());
            }
            if (ddService.checkAccount(ppaccount)) {
                return JsonResult.getErrorResult("账号已存在，请重新输入！");
            }

            return ddService.add(mmUser) == true ? JsonResult.getSuccessResult("新增人员信息成功")
                    : JsonResult.getErrorResult("新增人员信息失败");

        } catch (Exception e) {
            e.printStackTrace();
            log.error("user/add:error",e);
            return JsonResult.getErrorResult("user/add:error " + e.getMessage());
        }
    }
    @RequestMapping("modify")
    public JsonResult<?> modify(@RequestParam("userID") String ppUserId,
                                @RequestParam("username") String ppusername,
                                @RequestParam("account") String ppaccount,
                                @RequestParam("password") String pppassword,
                                @RequestParam("buzhibie") String ppbuzhibie,
                                HttpServletRequest request) {

        try {
            Ysuser mmUser =ddService.findOne(ppUserId);
            if(mmUser==null){
                return JsonResult.getErrorResult("user/modify:error ");
            }

            BooleanMessage mmBooleanMessage = checkInputData(mmUser,ppusername,ppaccount,pppassword,ppbuzhibie);
            if (!mmBooleanMessage.isOk()) {
                log.error("usere/modify:error",mmBooleanMessage.getMessage().toString());
                return JsonResult.getErrorResult(mmBooleanMessage.getMessage().toString());
            }
            if (ddService.checkAccountByuserid(ppaccount,ppUserId)) {
                return JsonResult.getErrorResult("账号存在，请重新输入！");
            }
            mmUser.setUpdatetime(new Date());
            HttpSession session = request.getSession();
            mmUser.setUpdateby(session.getAttribute("Id").toString());
            return ddService.modify(mmUser) == true ? JsonResult.getSuccessResult("修改人员信息成功")
                    : JsonResult.getErrorResult("修改人员信息失败");

        } catch (Exception e) {
            e.printStackTrace();
            log.error("user/modify:error",e);
            return JsonResult.getErrorResult("user/modify:error " + e.getMessage());
        }

    }

    @RequestMapping("modifypsw")
    public JsonResult<?> modifypsw(@RequestParam("userID") String ppUserId,
                                @RequestParam("password") String pppassword,
                                HttpServletRequest request) {

        try {
            Ysuser mmUser =ddService.findOne(ppUserId);
            if(mmUser==null){
                return JsonResult.getErrorResult("user/modify:error ");
            }

            mmUser.setPassword(pppassword);
            mmUser.setShifouxiugai("1");
            mmUser.setUpdatetime(new Date());
            HttpSession session = request.getSession();
            mmUser.setUpdateby(session.getAttribute("Id").toString());
            return ddService.modify(mmUser) == true ? JsonResult.getSuccessResult("修改人员信息成功")
                    : JsonResult.getErrorResult("修改人员信息失败");

        } catch (Exception e) {
            e.printStackTrace();
            log.error("user/modify:error",e);
            return JsonResult.getErrorResult("user/modify:error " + e.getMessage());
        }

    }


    @RequestMapping("delete")
    public JsonResult<?> delete(@RequestParam("userID") String ppUserId) {
        try {
            return ddService.delete(ppUserId) == true ? JsonResult.getSuccessResult("删除人员信息成功")
                    : JsonResult.getErrorResult("删除人员信息失败");
        }catch (Exception e) {
            e.printStackTrace();
            log.error("user/delete:error",e);
            return JsonResult.getErrorResult("user/delete:error " + e.getMessage());
        }
    }


    private BooleanMessage checkInputData(Ysuser mmUser, String ppusername, String ppaccount, String pppassword,String ppbuzhibie) {
        if (StringHandle.getStringByteLength(ppusername) > 100) {
            return BooleanMessage.getErrorMessage("姓名不能超过100字节");
        }
        if (StringHandle.getStringByteLength(ppaccount) > 100) {
            return BooleanMessage.getErrorMessage("账号不能超过100字节");
        }
        if (StringHandle.getStringByteLength(pppassword) > 100) {
            return BooleanMessage.getErrorMessage("密码不能超过100字节");
        }
        if (StringHandle.getStringByteLength(ppbuzhibie) > 100) {
            return BooleanMessage.getErrorMessage("军衔不能超过100字节");
        }


        mmUser.setUsername(ppusername);
        mmUser.setAccount(ppaccount);
        mmUser.setPassword(pppassword);
        mmUser.setBuzhibie(ppbuzhibie);
        mmUser.setUsertype("zj");
        return BooleanMessage.getSuccessMessage(mmUser);
    }

}
